/* global console, openjpeg */

(function () {
  'use strict';
  // debugger
  console.log(8888888888888)
  var renderEvent = new Event('jp2-polyfill-render');

  function loadOpenJPEG() {
    var s = document.createElement('script');

    if (s.addEventListener) {
      s.addEventListener('load', initPolyfill, false);
    } else if (s.readyState) {
      // IE 10 and worse:
      s.onreadystatechange = function () {
        if (s.readyState == 'loaded' || s.readyState == 'complete') {
          initPolyfill();
        }
      };
    }
    s.setAttribute("data-callType","callScript0");
    s.src = '/html/external/openjpeg.js';

    var firstScript = document.getElementsByTagName('head')[0];
    firstScript.parentNode.insertBefore(s, firstScript);
  }

  function initPolyfill() {
    console.log('JPEG-2000 polyfill loading');

    updateImageTags();
    updateBackgroundImages();

    console.log('JPEG-2000 polyfill complete');
  }

  function updateImageTags() {
    var imgs = document.querySelectorAll('.jp2-img2 img');
    // console.log(imgs,'imgs');
    // console.log('ctx')
    for (var i = 0; i < imgs.length; i++) {
      var img = imgs[i];
      img.crossOrigin = "Anonymous";
      // TODO: simply require a data- attribute or src ends with .jp2/j2k?

      if (img.complete && img.naturalWidth !== undefined && img.naturalWidth > 0) {
        console.log('Skipping loaded', img);
        continue;
      }

      var canvas = createCanvasFromUrl(img.src, shouldDisplayStats(img));
      canvas.id = img.id;
      canvas.className = img.className;

      if (img.attributes.style) {
        canvas.setAttribute('style', img.attributes.style.value);
      }

      if (img.style.display) {
        canvas.style.display = img.style.display;
      } else {
        canvas.style.display = 'inline';
      }

      // TODO: don't punt on non-pixel measurements:
      if (img.attributes.height) {
        canvas.height = parseInt(img.attributes.height.value, 10);
        canvas.style.height = canvas.height + "px";
      }

      if (img.attributes.width) {
        canvas.width = parseInt(img.attributes.width.value, 10);
        canvas.style.width = canvas.width + "px";
      }

      // TODO: auto scale if only one dimension is specified

      // FIXME: copy computed styles or punt outright?

      // 绘画完之后再改变canvas样式大小
      let jp2ListWidth = window.jp2ListWidth;
      let jp2ListHeight = window.jp2ListHeight;
      // 只显示一张
      // if (i % 3 != 0) {
      //   canvas.style.display = 'none';
      // }

      // 只有一张图的
      if (imgs[i].getAttribute('type') == 'normal') {
        canvas.style = `width:${jp2ListWidth};maxHeight:${jp2ListHeight};`
      }else {
        // 第一张
        // if (i % 3 == 0) {
        //   canvas.style = `width:${jp2ListWidth};maxHeight:${jp2ListHeight};position:absolute;z-index:3;left:16px;top:24px;`
        // }
        // //第二张
        // if ((i - 1) % 3 == 0) {
        //   canvas.style = `width:${jp2ListWidth};maxHeight:${jp2ListHeight};position:absolute;z-index:2;left:8px;top:12px;`
        // }
        // //第三张
        // if ((i - 2) % 3 == 0) {
        //   canvas.style = `width:${jp2ListWidth};maxHeight:${jp2ListHeight};position:absolute;z-index:1;top:0;`
        // }
      }
      // img.parentNode.insertBefore(canvas, img.nextSibling);
      canvas.style = "margin-bottom:5px;"
      img.parentNode.replaceChild(canvas, img);
    }
  }

  function createCanvasFromUrl(src, displayStats) {
    var canvas = document.createElement('canvas'),
      xhr = new XMLHttpRequest(),
      fileType = (src.indexOf('.j2k') > -1) ? 'j2k' : 'jp2';

    xhr.open('GET', src);
    xhr.responseType = 'arraybuffer';
    xhr.onreadystatechange = function() {
      if (xhr.readyState !== 4) {
        return;
      }

      if (xhr.status !== 200 && xhr.status !== 0) {
        throw "Unable to load image data: XHR status " + xhr.status + " for " + src;
      }

      var bytes = new Uint8Array(xhr.response),
        imageRGB, imageRGBA,
        startTime, decodeTime, renderTime;

      startTime = Date.now();
      imageRGB = openjpeg(bytes, fileType); // 返回data为空 错误图片解析报错
      console.log('imageRGB-xx',imageRGB);
      decodeTime = Date.now() - startTime;
      canvas.polyfillDecodeSeconds = decodeTime / 1000;

      // console.log(imageRGB); 解析之后的真实图片

      startTime = Date.now();
      canvas.width = imageRGB.width;
      canvas.height = imageRGB.height;

      var ctx = canvas.getContext('2d'),
        pixelsPerChannel = imageRGB.width * imageRGB.height;

      // 标记是否是正确的jp2图片地址
      if (imageRGB.height == 0 && imageRGB.width == 0) {
        canvas.setAttribute('is-false-img', true);
        canvas.style.display = 'none';
      }
      console.log('ctx',ctx.createImageData)
      console.log('ctximageRGB',imageRGB)
      imageRGBA = ctx.createImageData(imageRGB.width?imageRGB.width:1920, imageRGB.height?imageRGB.height:1080);

      // FIXME: handle alpha channel
      // FIXME: handle different color depths and layouts

      var i = 0,
        j = 0;
      while (i < imageRGBA.data.length && j < pixelsPerChannel) {
        imageRGBA.data[i] = imageRGB.data[j]; // R
        imageRGBA.data[i + 1] = imageRGB.data[j + pixelsPerChannel]; // G
        imageRGBA.data[i + 2] = imageRGB.data[j + (2 * pixelsPerChannel)]; // B
        imageRGBA.data[i + 3] = 255; // A

        // Next pixel
        i += 4;
        j += 1;
      }

      ctx.putImageData(imageRGBA, 0, 0);

      renderTime = Date.now() - startTime;
      canvas.polyfillRenderSeconds = renderTime / 1000;

      if (!!displayStats) {
        ctx.miterLimit = 2;
        ctx.lineJoin = 'circle';

        var message = 'Decode: ' + canvas.polyfillDecodeSeconds.toFixed(2) + 's; ' +
          'Render: ' + canvas.polyfillRenderSeconds.toFixed(2) + 's';

        ctx.font = '16px monospace';
        ctx.fillStyle = '#cccccc';
        ctx.lineWidth = 3;
        ctx.strokeText(message, 5, canvas.height - 5, canvas.width);
        ctx.fillStyle = '#99cc99';
        ctx.lineWidth = 1;
        ctx.fillText(message, 5, canvas.height - 5, canvas.width);
      }

      canvas.dispatchEvent(renderEvent);
    };
    xhr.send(null);
    return canvas;
  }

  // Converts canvas to an image
  function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/jpeg");
    return image;
  }

  function updateBackgroundImages() {
    // There's no efficient way to do this without using something like a class to opt-in
    // and scanning every element seems a bit wasteful
    var elements = document.querySelectorAll('.jp2-background-image');

    for (var i = 0; i < elements.length; i++) {
      var element = elements[i],
        url = window.getComputedStyle(element, false).backgroundImage.slice(4, -1);

      url = url.replace(/^(['"])(.+)\1$/, '$2');

      var canvas = createCanvasFromUrl(url, shouldDisplayStats(element));

      // The element must be in the DOM to render but it can be hidden:
      canvas.style.display = 'none';
      document.body.appendChild(canvas);

      var id = 'jp2-polyfill-' + i;

      if ('getCSSCanvasContext' in document) {
        element.style.backgroundImage = '-webkit-canvas(' + id + ')';
        canvas.addEventListener('jp2-polyfill-render', function () {
          var ctx = document.getCSSCanvasContext('2d', id, canvas.width, canvas.height);
          ctx.drawImage(canvas, 0, 0);
        });
      } else {
        canvas.id = id;
        element.style.backgroundImage = '-moz-element(#' + id + ')';
      }
    }
  }

  function shouldDisplayStats(elem) {
    return elem.getAttribute('data-display-polyfill-info') == 'true';
  }

  // There's no standard way to detect the image formats supported by the current browser
  // so we'll create a test image and

  var img = new Image();
  img.onerror = img.load = function () {
    if (!img.width || img.width === 0) {
      console.log('Polyfill appears to be necessary:', img.width, img.height);
      loadOpenJPEG();
    }
  };

  // This is a 4px image because OpenJPEG does not appear to support 1px:
  img.src = '';
})();

